package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * 2471. 逐层排序二叉树所需的最少操作数目
 *
 * @author liw
 * @version 1.0
 * @date 2022/11/14 17:27
 */
public class MinimumOperations {

    public static void main(String[] args) {
        MinimumOperations test = new MinimumOperations();
        test.arr1 = new int[]{7, 6, 8, 5};
        test.arr2 = new int[]{7, 6, 8, 5};
        int i = test.find(4);
        System.out.println(i);


    }

    private int[] nums = new int[100001];
    private int[] arr1 = new int[50001];
    private int[] arr2 = new int[50001];

    public int minimumOperations(TreeNode root) {
        LinkedList<TreeNode> list = new LinkedList<>();
        list.addLast(root);
        int count = 0;
        while (!list.isEmpty()) {
            int size = list.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = list.pollFirst();
                if (node.left != null) {
                    list.add(node.left);
                }
                if (node.right != null) {
                    list.add(node.right);
                }
                arr1[i] = node.val;
                arr2[i] = node.val;
            }
            count += find(size);
        }
        return count;
    }

    private int find(int size) {
        Arrays.sort(arr1, 0, size);
        for (int i = 0; i < size; i++) {
            nums[arr2[i]] = i;
        }
        int count = 0;
        for (int i = 0; i < size; i++) {
            if (arr1[i] != arr2[i]) {
                int index = nums[arr1[i]];
                arr2[index] = arr2[i];
                nums[arr2[i]] = index;
                count++;
            }
        }
        return count;
    }

}
